import dayjs from 'dayjs'

/**
 * @description 获取url中的参数
 */
export const getUrlParams = (url: string) => {
    const arr = url.split('?')[1].split('&')
    const res: any = {}
    arr.forEach(item => {
        const keyValue = item.split('=')
        res[keyValue[0]] = keyValue[1]
    })
    return res
}

/**
 * @description 是否外链
 */
export const isExternal = (path: any) => {
    return /^(https?:|mailto:|tel:)/.test(path)
}

/**
 * 将数组转换成Map类型
 * @param arr 数据源
 * @param field key值
 */
export const toMap = (arr: any = [], field: string | number) => {
    const map = new Map()
    arr.forEach((item: any) => {
        map.set(item[field], item)
    })
    return map
}

/**
 * 将Map对象转换成数组类型
 * @param map 数据源
 */
export const toArray = (map: any = new Map()) => {
    const arr: any = []
    map.forEach((item: any) => {
        arr.push(item)
    })
    return arr
}

/**
 * 分组
 */
export const groupBy = (data: any[], field: string, format?: string) => {
    let map = new Map()
    data.forEach((item: any, key: number) => {
        const code = format ? dayjs(item[field]).format(format) : item[field]
        const arr = map.get(code) || []
        arr.push(item)
        map.set(code, arr)
    })
    return map
}

/**
 * 生成随机数
 */
export const randomNum = (min: number, max: number) => {
    min = Math.ceil(min)
    max = Math.floor(max)
    return Math.floor(Math.random() * (max - min + 1)) + min //含最大值，含最小值
}
